package com.shanxi.cz.module.biz.service.ammeterrecordday;

import com.shanxi.cz.framework.common.pojo.PageResult;
import com.shanxi.cz.framework.common.util.object.BeanUtils;
import com.shanxi.cz.module.biz.controller.admin.ammeterrecordday.vo.AmmeterRecordDayPageReqVO;
import com.shanxi.cz.module.biz.controller.admin.ammeterrecordday.vo.AmmeterRecordDaySaveReqVO;
import com.shanxi.cz.module.biz.controller.admin.ammeterrecordday.vo.CompareDayRecordRespVO;
import com.shanxi.cz.module.biz.dal.dataobject.ammeterrecordday.AmmeterRecordDayDO;
import com.shanxi.cz.module.biz.dal.dataobject.ammeterrecordmonth.AmmeterRecordMonthDO;
import com.shanxi.cz.module.biz.dal.dataobject.ammeterrecordyear.AmmeterRecordYearDO;
import com.shanxi.cz.module.biz.dal.mysql.ammeterrecordday.AmmeterRecordDayMapper;
import com.shanxi.cz.module.biz.service.ammeterrecordmonth.AmmeterRecordMonthService;
import com.shanxi.cz.module.biz.service.ammeterrecordyear.AmmeterRecordYearService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.shanxi.cz.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.shanxi.cz.module.biz.enums.ErrorCodeConstants.AMMETER_RECORD_DAY_NOT_EXISTS;

/**
 * 电表数据日报 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AmmeterRecordDayServiceImpl implements AmmeterRecordDayService {

    @Resource
    private AmmeterRecordDayMapper ammeterRecordDayMapper;

    @Resource
    private AmmeterRecordMonthService ammeterRecordMonthService;

    @Resource
    private AmmeterRecordYearService ammeterRecordYearService;

    @Override
    public Integer createAmmeterRecordDay(AmmeterRecordDaySaveReqVO createReqVO) {
        // 插入
        AmmeterRecordDayDO ammeterRecordDay = BeanUtils.toBean(createReqVO, AmmeterRecordDayDO.class);
        ammeterRecordDayMapper.insert(ammeterRecordDay);

        // 返回
        return ammeterRecordDay.getId();
    }

    @Override
    public void updateAmmeterRecordDay(AmmeterRecordDaySaveReqVO updateReqVO) {
        // 校验存在
        validateAmmeterRecordDayExists(updateReqVO.getId());
        // 更新
        AmmeterRecordDayDO updateObj = BeanUtils.toBean(updateReqVO, AmmeterRecordDayDO.class);
        ammeterRecordDayMapper.updateById(updateObj);
    }

    @Override
    public void deleteAmmeterRecordDay(Integer id) {
        // 校验存在
        validateAmmeterRecordDayExists(id);
        // 删除
        ammeterRecordDayMapper.deleteById(id);
    }

    @Override
    public void deleteAmmeterRecordDayListByIds(List<Integer> ids) {
        // 删除
        ammeterRecordDayMapper.deleteByIds(ids);
    }


    private void validateAmmeterRecordDayExists(Integer id) {
        if (ammeterRecordDayMapper.selectById(id) == null) {
            throw exception(AMMETER_RECORD_DAY_NOT_EXISTS);
        }
    }

    @Override
    public AmmeterRecordDayDO getAmmeterRecordDay(Integer id) {
        return ammeterRecordDayMapper.selectById(id);
    }

    @Override
    public AmmeterRecordDayDO getAmmeterRecordDay(Integer ammeterId, String recordDate) {
        return ammeterRecordDayMapper.selectOne(AmmeterRecordDayDO::getAmmeterId, ammeterId, AmmeterRecordDayDO::getRecordDate, recordDate);
    }

    @Override
    public List<AmmeterRecordDayDO> getAmmeterRecordDayByMonth(AmmeterRecordDayPageReqVO pageReqVO) {
        return ammeterRecordDayMapper.selectList(pageReqVO);
    }

    @Override
    public PageResult<AmmeterRecordDayDO> getAmmeterRecordDayPage(AmmeterRecordDayPageReqVO pageReqVO) {
        return ammeterRecordDayMapper.selectPage(pageReqVO);
    }

    @Override
    public CompareDayRecordRespVO compareDayRecord(AmmeterRecordDayPageReqVO pageReqVO) {
        CompareDayRecordRespVO compareDayRecordRespVO = new CompareDayRecordRespVO();
        // 当前日期
        String recordDate = pageReqVO.getRecordDate();
        compareDayRecordRespVO.setRequestDate(recordDate);
        // 电表id
        Integer ammeterId = pageReqVO.getAmmeterId();

        //****************  比较今天电量和昨天和去年今天的电量  start  ****************//

        // 昨天
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析字符串为日期
        LocalDate specifiedDate = LocalDate.parse(recordDate, formatter);
        // 获取前一天
        LocalDate previousDay = specifiedDate.minusDays(1);
        String previousDayStr = previousDay.format(formatter);
        compareDayRecordRespVO.setLastDayDate(previousDayStr);
        AmmeterRecordDayDO ammeterRecordPreviousDay = ammeterRecordDayMapper.selectOne(AmmeterRecordDayDO::getRecordDate, previousDayStr, AmmeterRecordDayDO::getAmmeterId, ammeterId);

        // 去年今天
        LocalDate lastYearDate = specifiedDate.minusYears(1);
        String lastYearDateStr = lastYearDate.format(formatter);
        compareDayRecordRespVO.setLastYearDate(lastYearDateStr);
        AmmeterRecordDayDO ammeterRecordLastYearDate = ammeterRecordDayMapper.selectOne(AmmeterRecordDayDO::getRecordDate, lastYearDateStr, AmmeterRecordDayDO::getAmmeterId, ammeterId);

        AmmeterRecordDayDO ammeterRecordDay = ammeterRecordDayMapper.selectOne(AmmeterRecordDayDO::getRecordDate, pageReqVO.getRecordDate(), AmmeterRecordDayDO::getAmmeterId, ammeterId);
        Double engThisDay = ammeterRecordDay.getEng();
        compareDayRecordRespVO.setEngThisDay(engThisDay);

        Double engThisLastYearDate;
        double onYearDateRate;
        if (null == ammeterRecordLastYearDate) {
            engThisLastYearDate = 0.00;
            onYearDateRate = 0.00;
        } else {
            engThisLastYearDate = ammeterRecordLastYearDate.getEng();
            onYearDateRate = calculatePercentageChange(engThisLastYearDate, engThisDay);
        }
        compareDayRecordRespVO.setEngLastYearDate(engThisLastYearDate);
        compareDayRecordRespVO.setOnYearDateRate(onYearDateRate);

        Double engPreviousDay;
        double chainLinkedRate;
        if (null == ammeterRecordPreviousDay) {
            engPreviousDay = 0.00;
            chainLinkedRate = 0.00;
        } else {
            engPreviousDay = ammeterRecordPreviousDay.getEng();
            chainLinkedRate = calculatePercentageChange(engPreviousDay, engThisDay);
        }
        compareDayRecordRespVO.setEngLastDay(engPreviousDay);
        compareDayRecordRespVO.setChainLinkedRate(chainLinkedRate);

        //****************  比较今天电量和昨天和去年今天的电量  end  ****************//

        //****************  比较上个月电量和上上个月的电量  start  ****************//
        // 格式化为 年-月 (例如: 2024-10)
        DateTimeFormatter formatterMonth = DateTimeFormatter.ofPattern("yyyy-MM");

//        LocalDate nowMonth = LocalDate.parse(recordDate, formatterMonth);
        String nowMonthStr = specifiedDate.format(formatterMonth);
        compareDayRecordRespVO.setNowMonth(nowMonthStr);

        // 查询本月的电量
        AmmeterRecordMonthDO ammeterRecordMonth = ammeterRecordMonthService.getAmmeterRecordMonth(1, nowMonthStr);
        Double engMonth = ammeterRecordMonth.getEng();
        compareDayRecordRespVO.setEngMonth(engMonth);

        // 获取上个月
        LocalDate lastMonth = specifiedDate.minusMonths(1);
        String lastMonthStr = lastMonth.format(formatterMonth);
        compareDayRecordRespVO.setLastMonth(lastMonthStr);

        // 查询上个月的电量
        AmmeterRecordMonthDO ammeterRecordLastMonth = ammeterRecordMonthService.getAmmeterRecordMonth(1, lastMonthStr);
        if (null != ammeterRecordLastMonth) {
            Double engLastMonth = ammeterRecordLastMonth.getEng();
            compareDayRecordRespVO.setEngLastMonth(engLastMonth);
        }


        // 获取上上个月
        LocalDate beforeLastMonth = specifiedDate.minusMonths(2);
        String beforeLastMonthStr = beforeLastMonth.format(formatterMonth);
        compareDayRecordRespVO.setBeforeLastMonth(beforeLastMonthStr);

        // 查询上上个月的电量
        AmmeterRecordMonthDO ammeterRecordBeforeLastMonth = ammeterRecordMonthService.getAmmeterRecordMonth(1, beforeLastMonthStr);
        if (null != ammeterRecordBeforeLastMonth) {
            Double engBeforeLastMonth = ammeterRecordBeforeLastMonth.getEng();
            compareDayRecordRespVO.setEngBeforeLastMonth(engBeforeLastMonth);
        }

        // 计算月度同比
        if (null != compareDayRecordRespVO.getEngLastMonth() && null != compareDayRecordRespVO.getEngBeforeLastMonth()) {
            double onMonthRate = calculatePercentageChange(compareDayRecordRespVO.getEngBeforeLastMonth(), compareDayRecordRespVO.getEngLastMonth());
            compareDayRecordRespVO.setOnMonthRate(onMonthRate);
        } else {
            compareDayRecordRespVO.setOnMonthRate(0.00);
        }

        //****************  比较上个月电量和上上个月的电量  end  ****************//


        //****************  比较去年和前年的电量  start  ****************//
        // 格式化为 年-月 (例如: 2024-10)
        DateTimeFormatter formatterYear = DateTimeFormatter.ofPattern("yyyy");

//        LocalDate nowYear = LocalDate.parse(recordDate, formatterYear);
        String nowYearStr = specifiedDate.format(formatterYear);
        compareDayRecordRespVO.setNowYear(nowYearStr);

        // 查询今年的电量
        AmmeterRecordYearDO ammeterRecordYear = ammeterRecordYearService.getAmmeterRecordYear(1, nowYearStr);
        Double engYear = ammeterRecordYear.getEng();
        compareDayRecordRespVO.setEngYear(engYear);

        // 获取去年
        LocalDate lastYear = specifiedDate.minusYears(1);
        String lastYearStr = lastYear.format(formatterYear);
        compareDayRecordRespVO.setLastYear(lastYearStr);

        // 查询去年的电量
        AmmeterRecordYearDO ammeterRecordLastYear = ammeterRecordYearService.getAmmeterRecordYear(1, lastYearStr);
        if(null != ammeterRecordLastYear){
            Double engLastDay = ammeterRecordLastYear.getEng();
            compareDayRecordRespVO.setEngLastDay(engLastDay);
        }

        // 获取前年
        LocalDate beforeLastYear = specifiedDate.minusYears(2);
        String beforeLastYearStr = beforeLastYear.format(formatterYear);
        compareDayRecordRespVO.setBeforeLastYear(beforeLastYearStr);

        // 查询前年的电量
        AmmeterRecordYearDO ammeterRecordBeforeLastYear = ammeterRecordYearService.getAmmeterRecordYear(1, beforeLastYearStr);
        if(null != ammeterRecordBeforeLastYear){
            Double engBeforeLastDay = ammeterRecordBeforeLastYear.getEng();
            compareDayRecordRespVO.setEngBeforeLastYear(engBeforeLastDay);
        }

        // 计算年度同比
        if (null != compareDayRecordRespVO.getEngLastYear() && null != compareDayRecordRespVO.getEngBeforeLastYear()) {
            double onYearRate = calculatePercentageChange(compareDayRecordRespVO.getEngBeforeLastYear(), compareDayRecordRespVO.getEngLastYear());
            compareDayRecordRespVO.setOnYearRate(onYearRate);
        } else {
            compareDayRecordRespVO.setOnYearRate(0.00);
        }

        //****************  比较去年和前年的电量  end  ****************//

        return compareDayRecordRespVO;
    }

    public static double calculatePercentageChange(double oldValue, double newValue) {
        if (oldValue == 0) {
            throw new ArithmeticException("除数不能为零");
        }

        double change = newValue - oldValue;
        double percentage = (change / oldValue) * 100;

        // 四舍五入保留两位小数
        return Math.round(percentage * 100.0) / 100.0;
    }

}